import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    DeviceEventEmitter
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import StatusBarSelf from '../../components/StatusBarSelf';
import { getImgUrl } from '../../utils/ComFunction'
import Loading from "../../utils/Loading";
import CommonAlertView from "../common/CommonAlertView";
import AsyncImage from '../../components/image/AsyncImage'


const screenW = Dimensions.get('window').width;
let navigation

export default class CompanyEmployee extends Component {
    constructor(props) {
        super(props);
        this.state = {
            keyword: '',
            dataArray: [],
            totalArray: [],
            isRefresh: false,
            contacters: [],
            showAlertView: false,
        }
    }

    componentWillUnmount() {
        this.deleteListener.remove();
    }

    componentWillMount() {
        this.deleteListener = DeviceEventEmitter.addListener('deleteStaffSuccess', (employee) => {
            let totalArray = []
            this.state.totalArray.map((item) => {
                if (item.userId != employee.userId) {
                    totalArray.push(item)
                }
            })
            this.setState({
                totalArray: totalArray,
                dataArray: totalArray
            })
        });
    }

    componentDidMount() {

        if (this.Loading) {
            this.Loading.show();
        }
        this.getMerchantUnionContact(true)
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <StatusBarSelf />
                <View style={[styles.toplayout, { height: Constant.navigationBarHeight }]}>
                    <TouchableOpacity
                        style={styles.fanhuibox}
                        activeOpacity={0.8}
                        onPress={this.finish}>
                        <Image source={require('source/image/comm/back.png')} style={styles.fanhui} />
                    </TouchableOpacity>

                    <View style={styles.inputBox}>
                        <Image source={require('source/image/comm/icon_sc_search.png')} style={styles.searchIcon} />
                        <TextInput
                            clearButtonMode='while-editing'
                            style={styles.textInput}
                            placeholder='员工名称'
                            returnKeyType='search'
                            value={this.state.keyword}
                            onEndEditing={() => {
                                this.startSearch()
                            }}
                            onChangeText={this.onChangeTextHandle}
                            onSubmitEditing={() => {
                                this.startSearch()
                            }}
                        />
                    </View>

                    <TouchableOpacity
                        style={styles.addbox}
                        activeOpacity={0.8}
                        onPress={() => {
                            this.allowAddStaff()
                        }}>
                        <Image source={require('source/image/customer_add.png')} style={styles.add} />
                    </TouchableOpacity>

                </View>

                {this.renderList()}

                {
                    this.state.showAlertView ?
                        <CommonAlertView
                            title={'温馨提示'}
                            notice={'您添加的员工数量已到达上限，如有需要请联系客服人员。'}
                            sureDes={'联系客服'}
                            cancelDes={'取消'}
                            sureAction={() => {
                                this.setState({
                                    showAlertView: false,
                                }, function () {
                                    this.call()
                                })
                            }}
                            cancelAction={() => {
                                this.setState({
                                    showAlertView: false,
                                })
                            }}
                        />
                        : null
                }

                <Loading onRef={(ref) => (this.Loading = ref)} />
            </View>
        )
    }

    renderList() {
        return (
            <View style={{ flex: 1 }}>
                <FlatList
                    data={this.state.dataArray}
                    ListHeaderComponent={this.header.bind(this)}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    header() {
        return (
            <View style={{ height: 40, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, }}>
                <Text style={{ fontSize: 14, color: '#ED542E' }}>请设置联系人，接待车商在线车辆咨询</Text>
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <TouchableOpacity
                style={styles.itemContain}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('CompanyEmployeeDetail', {
                        employee: JSON.stringify(item),
                        totalEmployees: JSON.stringify(this.state.totalArray),
                        completion: (employee) => {
                            let totalArray = []
                            this.state.totalArray.map((item) => {
                                if (item.userId == employee.userId) {
                                    employee.isExisted = employee.isUnionContact == 1 ? true : false
                                    totalArray.push(employee)
                                } else {
                                    totalArray.push(item)
                                }
                            })
                            this.setState({
                                totalArray: totalArray,
                                dataArray: totalArray
                            })
                            this.getMerchantUnionContact(false)
                        }
                    })
                }
                }
            >
                <AsyncImage
                    source={{ uri: getImgUrl(item.face) }}
                    defaultSource={require('source/image/userIcon.png')}
                    style={styles.head}
                    resizeMode="cover"
                />
                <View style={styles.infoBox}>
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={styles.nameText}>{item.fullname}</Text>
                        {
                            item.isExisted ?
                                <Image style={styles.img} source={require('source/image/icon_contacter_logo.png')} />
                                :
                                null
                        }
                    </View>
                    <Text style={styles.jobText}>{'职务:' + item.job}</Text>
                    <Text style={styles.jobText}>{'电话:' + item.userPhone}</Text>
                </View>
                {
                    item.staffStatus == 1 ?
                        null
                        :
                        <Image style={styles.leave} source={require('source/image/icon_leave_job.png')} />

                }
                <View style={styles.sepLine} />
            </TouchableOpacity>
        )
    }

    finish() {
        navigation.goBack();
    }

    allowAddStaff() {
        if (this.Loading) {
            this.Loading.show();
        }
        let param = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.allowAddStaff, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data
                if (data) {
                    navigation.navigate('CompanyEmployeeEdit', {
                        isAdd: true,
                        completion: (employee) => {
                            this.getCompanyEmployee()
                        }
                    })
                } else {
                    this.setState({
                        showAlertView: true,
                    })
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    refreshData = () => {
        this.getCompanyEmployee();
    }

    getCompanyEmployee() {
        this.setState({ isRefresh: true })
        let param = {
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
        }
        let that = this
        HttpUtils.postRequest(HttpUrls.queryStaffList, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            that.state.contacters.map((contacter) => {
                                if (item.userId == contacter.userId) {
                                    item.isExisted = true;
                                }
                            }
                            )
                        });
                        this.setState({
                            dataArray: resultList,
                            totalArray: resultList,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getMerchantUnionContact(first) {
        let param = {
            merchantId: Constant.userInfo.merchantId,
        }
        HttpUtils.getRequest(HttpUrls.getMerchantUnionContact, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    this.setState({
                        contacters: data
                    }, function () {
                        if (first) {
                            this.getCompanyEmployee()
                        }
                    }
                    )
                } else {
                    if (this.Loading) {
                        this.Loading.hide();
                    }
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    call() {
        let param = {
            key: 'shuaicheTelephone',
        }
        HttpUtils.getRequest(HttpUrls.configProperties, param)
            .then((result) => {
                let data = result.data
                if (data) {
                    const url = `tel:${data.shuaicheTelephone}`;
                    Linking.canOpenURL(url).then(supported => {
                        if (!supported) {
                            return Alert.alert('提示', `您的设备不支持该功能，请手动拨打 ${data.shuaicheTelephone}`, [
                                { text: '确定' }
                            ]);
                        }
                        return Linking.openURL(url);
                    }).catch(err => Alert(err));
                }
            })
            .catch((error) => {

            });
    }

    onChangeTextHandle = (value) => {
        this.setState({
            keyword: value
        })
    }

    startSearch() {

        if (this.state.keyword) {
            let dataArray = this.state.totalArray
            let temp = []
            dataArray.map((item) => {
                if (item.fullname.indexOf(this.state.keyword) >= 0 || item.userPhone.indexOf(this.state.keyword) >= 0) {
                    temp.push(item)
                }
            })
            this.setState({
                dataArray: temp,
            })
        } else {
            this.setState({
                dataArray: this.state.totalArray,
            })
        }
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    toplayout: {
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ffffff'
    },
    fanhuibox: {
        position: 'absolute',
        width: 60,
        height: '100%',
        left: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    fanhui: {
        width: 18,
        height: 16,
        marginLeft: 18,
    },
    inputBox: {
        position: 'absolute',
        left: 60,
        right: 60,
        height: 32,
        backgroundColor: '#F9F9F9',
        borderRadius: 4,
        paddingHorizontal: 10,
        flexDirection: 'row',
        alignItems: 'center'
    },
    searchIcon: {
        width: 14,
        height: 14,
    },
    textInput: {
        marginLeft: 10,
        color: '#333333',
        fontSize: 13,
        height: '100%',
        flex: 1,
        padding: 0
    },
    addbox: {
        position: 'absolute',
        width: 60,
        height: '100%',
        right: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    add: {
        width: 20,
        height: 20,
        marginLeft: 20,
    },

    itemContain: {
        paddingHorizontal: 15,
        width: '100%',
        height: 125,
        backgroundColor: '#fff',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    head: {
        width: 90,
        height: 90,
        borderRadius: 45,
        backgroundColor: '#F9F9F9',
    },
    infoBox: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-start',
        marginLeft: 18,
    },
    nameText: {
        fontSize: 17,
        color: '#333333',
        lineHeight: 22,
    },
    img: {
        marginLeft: 5,
        width: 43,
        height: 15
    },
    jobText: {
        fontSize: 14,
        color: '#5E5E5E',
        marginTop: 10
    },
    leave: {
        width: 73,
        height: 48,
        position: 'absolute',
        right: 0,
        top: 12,
    },
    sepLine: {
        position: 'absolute',
        bottom: 0,
        left: 15,
        width: screenW - 15,
        height: 0.5,
        backgroundColor: '#e4e4e4',
    }
})